#! /usr/bin/python
# -*- coding: utf-8 -*-
# author: nemokingdom@gmail.com

import StringIO
from ftplib import FTP
import sys, os
import string

class parseDir(object):
    def __init__(self, dirs):
        self.li = dirs.split('\n')[2:-1]
    def isDir(self,s):
        return s[0] == 'd'
    def getDirs(self):
        self.dirs = [string.split(w,maxsplit = 8)[-1] for w in self.li if self.isDir(w)]
        return self.dirs
    def getFiles(self):
        self.files = [string.split(w,maxsplit = 8)[-1] for w in self.li if not self.isDir(w)]
        return self.files
fopen = open('list.txt', 'w')

queue = []
def bfs(ftp):
    while(len(queue) != 0):
        pwd = queue.pop(0)
        ftp.cwd(pwd)
        old_stdout=sys.stdout
        output = StringIO.StringIO()
        sys.stdout = output
        ftp.dir()
        sys.stdout=old_stdout
        directory = output.getvalue().decode('gb18030')
        pD = parseDir(directory)
        
        #parse files
        for filei in pD.getFiles():
            print 'parse file:',
            print filei
            
        #parse dirs
        for direc in pD.getDirs():
            print 'parse directory:',
            print direc
            path = os.path.join(pwd.decode('gb18030'),direc)
            fopen.write(path.encode('utf-8')+'\n')
            queue.append(os.path.join(pwd.decode('gb18030'),direc).encode('gb18030'))

def main():
    ftp = FTP()
    ftp.connect('202.117.54.250','4021')
    ftp.login('list','list')
    queue.append('/')
    print queue
    bfs(ftp)
    fopen.close()

    ftp.close()
    print 'done'
if __name__ == '__main__':
    main()
